package cn.pomit.springbootwork.lock.support.service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.pomit.springbootwork.lock.support.dao.TGoodInfoDao;
import cn.pomit.springbootwork.lock.support.dao.TGoodLogDao;
import cn.pomit.springbootwork.lock.support.model.TGoodInfo;
import cn.pomit.springbootwork.lock.support.model.TGoodLog;

@Service
public class GoodsInfoService {
	public static final int STATUS_OK = 0;

	public static final int STATUS_ = 0;

	public static int count = 0;

	@Autowired
	TGoodInfoDao tGoodInfoDao;

	@Autowired
	TGoodLogDao tGoodLogDao;

	public TGoodInfo takeOne(Integer id) {

		return tGoodInfoDao.findById(id).orElse(null);
	}

	public Page<TGoodInfo> findPage(int page, int size) {
		Pageable pageable = PageRequest.of(page, size);
		return tGoodInfoDao.findAll(pageable);
	}

	public int consume(Integer goodId, Integer num) {
		TGoodInfo tGoodInfo = tGoodInfoDao.findById(goodId).orElse(null);

		if (tGoodInfo == null)
			return -1;

		if (tGoodInfo.getGoodNum() < 1)
			return -2;

		int leftNum = tGoodInfo.getGoodNum() - num;

		tGoodInfo.setGoodNum(leftNum);
		tGoodInfo.setUpdateNum(++count);

		tGoodInfoDao.save(tGoodInfo);

		TGoodLog entity = new TGoodLog();
		entity.setConsumeNum(num);
		entity.setCreateTime(new Date());
		entity.setGoodId(goodId);
		entity.setLeftNum(leftNum);
		tGoodLogDao.save(entity);

		return leftNum;
	}
}
